﻿using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Series;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Sigma.Admin.Client.GrpcService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sigma.Admin.Client.ViewModels
{
    [RegionMemberLifetime(KeepAlive = false)]
    public class OxyChartViewModel: BindableBase,IDisposable
    {
        private readonly ChartService _grpcService;
        private LineSeries _series1;
        private LineSeries _series2;
        public OxyChartViewModel(ChartService grpcService)
        {
            _grpcService = grpcService;
            GetChartCommand = new DelegateCommand<string>(Excute);
            InitData();
        }

        private void InitData()
        {
            Model = new PlotModel() { Title = "Simple Example", Subtitle = "using OxyPlot" };
            _series1 = new LineSeries { Title = "温度", MarkerType = MarkerType.Circle, Smooth = true };
            _series2 = new LineSeries { Title = "湿度", MarkerType = MarkerType.Star, Smooth = true, MarkerStroke = OxyColors.Red };
            var dateTimeAxis1 = new DateTimeAxis();
            dateTimeAxis1.Title = "Time";
            Model.Axes.Add(dateTimeAxis1);
            Model.Series.Add(_series1);
            Model.Series.Add(_series2);
        }

        private PlotModel _model;
        /// <summary>
        /// PlotModel
        /// </summary>
        public PlotModel Model
        {
            get { return _model; }
            set { _model = value; RaisePropertyChanged(); }
        }

        public DelegateCommand<string> GetChartCommand { get; set; }



        public void ExcuteSend()
        {
            Task.Run(async () =>
            {
                var res = _grpcService.GetChartAsync();
                await foreach (var line in res)
                {
                    _series1.Points.Add(DateTimeAxis.CreateDataPoint(line.Date.ToDateTime(), line.X));
                    _series2.Points.Add(DateTimeAxis.CreateDataPoint(line.Date.ToDateTime(), line.Y));
                    if (_series1.Points.Count > 60)
                    {
                        _series1.Points.RemoveAt(0);
                        _series2.Points.RemoveAt(0);
                    }
                    Model.InvalidatePlot(true);
                }
            });

        }

        public void Excute(string param)
        {
            switch (param)
            {
                case "SendRequest":
                    ExcuteSend(); break;
                case "Cancel":
                    ExcuteCancel(); break;
            }
        }

        private void ExcuteCancel()
        {
            _grpcService.StopStream();
        }

        public void Dispose()
        {
            _grpcService.Dispose();
        }
    }
}
